package com.qingsong.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.mybatisflex.core.query.QueryChain;
import com.mybatisflex.core.relation.RelationManager;
import com.mybatisflex.core.update.UpdateChain;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.qingsong.dto.SeasonInsertDTO;
import com.qingsong.dto.SeasonPageDTO;
import com.qingsong.dto.SeasonUpdateDTO;
import com.qingsong.entity.Season;
import com.qingsong.exception.ServiceException;
import com.qingsong.mapper.EpisodeMapper;
import com.qingsong.mapper.SeasonMapper;
import com.qingsong.service.SeasonService;
import com.qingsong.vo.SeasonSimpleListVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.mybatisflex.core.paginate.Page;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.List;

import static com.qingsong.entity.table.EpisodeTableDef.EPISODE;
import static com.qingsong.entity.table.SeasonTableDef.SEASON;

/**
 * 季次表 服务层实现。
 *
 * @author qingsong
 * @since 2024-12-22
 */
@Service
@CacheConfig(cacheNames = "season")
public class SeasonServiceImpl extends ServiceImpl<SeasonMapper, Season>  implements SeasonService{


    @Autowired
    private EpisodeMapper episodeMapper;

    @CacheEvict(allEntries = true)
    @Override
    public boolean insert(SeasonInsertDTO dto) {
        if (QueryChain.of(mapper)
                .where(SEASON.TITLE.eq(dto.getTitle()))
                .exists()) {
            throw new ServiceException("季次标题已存在");
        }
        Season season = BeanUtil.copyProperties(dto, Season.class);
        season.setCreated(LocalDateTime.now());
        season.setUpdated(LocalDateTime.now());
        return false;
    }

    @Cacheable(key = "#p0", condition = "#p0 != null", unless = "#result == null")
    @Override
    public Season select(Long id) {
        RelationManager.addQueryRelations("course", "category", "episodes");
        return mapper.selectOneWithRelationsById(id);
    }

    @Override
    @Cacheable(key = "#root.methodName", unless = "#result == null")
    public List<SeasonSimpleListVO> simpleList() {
        return QueryChain.of(mapper)
                .orderBy(SEASON.ID.desc(), SEASON.IDX.asc())
                .withRelations()
                .listAs(SeasonSimpleListVO.class);
    }

    @Override
    @Cacheable(key = "#root.methodName + ':' + #p0.toString()", unless = "#result == null")
    public Page<Season> page(SeasonPageDTO dto) {
        QueryChain<Season> queryChain = QueryChain.of(mapper)
                .orderBy(SEASON.IDX.asc(), SEASON.ID.desc());

        // title 条件
        String title = dto.getTitle();
        if (ObjectUtil.isNotNull(title)) {
            queryChain.where(SEASON.TITLE.like(title));
        }

        // courseId 条件
        Long courseId = dto.getFkCourseId();
        if (ObjectUtil.isNotNull(courseId)) {
            queryChain.where(SEASON.FK_COURSE_ID.eq(courseId));
        }

        return queryChain.withRelations()
                .page(new Page<>(dto.getPageNum(), dto.getPageSize()));
    }

    // 更新季次信息
    @CacheEvict(allEntries = true)
    @Override
    public boolean update(SeasonUpdateDTO dto) {
        // 标题查重
        if (QueryChain.of(mapper)
                .where(SEASON.TITLE.eq(dto.getTitle()))
                .and(SEASON.ID.ne(dto.getId()))
                .exists()) {
            throw new ServiceException("季次标题已存在");
        }
        // 组装 entity 实体类
        Season season = BeanUtil.copyProperties(dto, Season.class);
        season.setUpdated(LocalDateTime.now());
        return UpdateChain.of(season)
                .where(SEASON.ID.eq(season.getId()))
                .update();
    }
    @CacheEvict(allEntries = true)
    @Override
    public boolean delete(Long id) {
        // 通过季次主键查询全部集次的ID列表
        List<Long> seasonIds = QueryChain.of(episodeMapper)
                .select(EPISODE.ID)
                .where(EPISODE.FK_SEASON_ID.eq(id))
                .objListAs(Long.class);
        // 存在集次记录时，批量删除集次
        this.clearEpisode(seasonIds);
        // 删除课程
        return mapper.deleteById(id) > 0;
    }

    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(allEntries = true)
    @Override
    public boolean deleteBatch(List<Long> ids) {
        // 通过季次主键列表查询全部集次的ID列表
        List<Long> episodeIds = QueryChain.of(episodeMapper)
                .select(EPISODE.ID)
                .where(EPISODE.FK_SEASON_ID.in(ids))
                .objListAs(Long.class);

        // 批量删除集次
        this.clearEpisode(episodeIds);

        // 批量删除季次
        return mapper.deleteBatchByIds(ids) > 0;
    }

    /**
     * 根据集次ID列表，清空全部集次记录
     * @param episodeIds 集次主键列表
     */
    private void clearEpisode(List<Long> episodeIds) {
        if (ObjectUtil.isNotEmpty(episodeIds)) {
            if (episodeMapper.deleteBatchByIds(episodeIds) <= 0) {
                throw new ServiceException("集次删除失败");
            }
        }
    }

}
